/**
 * Created by xstnet on 2018/7/3.
 * Author: xstnet
 */
import React from 'react';
import { connect } from 'react-redux'
import { Table, Button, Switch, Modal, Form, Input, Icon, Popconfirm, Checkbox } from 'antd';
import { getUsers, changeUserStatus, getRoleBriefList, saveUsers, deleteUsers } from '@/api/Api.js'
import {getFormItemLayout, dateFormat } from "../../utils/CommonUtil";

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const formItemLayout = getFormItemLayout(24, 4, 24, 19);

const mapStateToProps = (state, ownProps) => ({
	users: state.Permission.users,
	config: state.common.config,
})

// rowSelection object indicates the need for row selection
const rowSelection = {
	onChange: (selectedRowKeys, selectedRows) => {
		console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
	},
};
const ADD_TITLE = <span className='modal-title'><Icon type='plus'/> 添加用户</span>
const EDIT_TITLE = <span className='modal-title'><Icon type='edit'/> 编辑用户</span>

class UserList extends React.Component {
	constructor(props) {
		super(props);
	}
	state = {
		loading: true,
		visible: false,
		actionTitle: ADD_TITLE,
		actionType: '',
		passwordPlaceholder: '',
		passwordChecked: true,
		nicknameChecked: false,
		roleList: [],
		checkedRoles: [],
		editUserIndex: '',
		pagination: {
			// pageSize: 10,
			total: 0,
			pageSizeOptions: ['10', '20', '30', '50', '100'],
			showSizeChanger: true,
			showQuickJumper: true,
			size: 'default',
			showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条， 共 ${total} 条`,
			onChange: (page, pageSize) => {
				this.handleGetUsers(page, pageSize)
			},
			onShowSizeChange: (page, pageSize) => {
				console.log(page);
				this.handleGetUsers(page, pageSize)
			}
		}
	}

	columns = [
		{ title: 'ID', dataIndex: 'id', },
		{ title: '用户名', dataIndex: 'username', },
		{ title: '昵称', dataIndex: 'nickname', },
		{ title: 'Emaill', dataIndex: 'emaill', },
		{ title: '登录次数', dataIndex: 'login_count', },
		{ title: '最后登录时间', dataIndex: 'login_at', render: (text)=>{return dateFormat(text)} },
		{ title: '最后登录IP', dataIndex: 'login_ip', },
		{
			title: '状态',
			align: 'center',
			dataIndex: 'status',
			width: 100,
			render: (text, record, index) => {
				return(<Switch onChange={this.handleChangeStatus.bind(this, record, index)} checked={parseInt(record.status) === 10} checkedChildren="启用" unCheckedChildren="禁用" />)
			},
		}, {
			title: '操作',
			align: 'center',
			key: 'operation',
			width: 180,
			render: (text, record, index) => {
				return (<span>
					<Button type="primary" style={{marginRight: 10}} onClick={this.onEdit.bind(this, record, index)} icon="edit" size='small'>编辑</Button>
					<Popconfirm title="Are you sure delete this user?" onConfirm={this.onDelete.bind(this, record.id, index)}  okText="Yes" cancelText="No">
						<Button type="danger" size='small' icon="delete" htmlType="button">删除</Button>
					</Popconfirm>
				</span>)
			},
		},
	];

	handleGetUsers = (page = 1, pageSize = 10) => {
		this.setState({loading: true})
		getUsers(page, pageSize).then(count => {
			this.setState({loading: false, pagination:{...this.state.pagination, total: count}})
		})
	}

	handleChangeStatus = (record, index, checked) => {
		console.log(this.props.users.count)
		changeUserStatus(record, index, checked).then(code => {
		})
	}

	/**
	 * 点击添加 响应
	 */
	onAdd = () => {
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: ADD_TITLE,
			actionType: 'add',
			checkedRoles: [],
			passwordPlaceholder: '请输入密码',
		});
		this.props.form.setFieldsValue(this.state.node);
	}
	/**
	 * 点击编辑 响应
	 */
	onEdit = (item, index) => {
		console.log(item)
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: EDIT_TITLE,
			actionType: 'save',
			checkedRoles: item.roles,
			passwordPlaceholder: '不修改密码请留空',
			editUserIndex: index,
		});
		item.password = '';
		this.props.form.setFieldsValue(item);
	}

	onDelete = (id, index) => {
		deleteUsers(id, index)
	}

	handleSave = (e) => {
		e.preventDefault();
		this.setState({
			passwordChecked: this.state.actionType === 'add',
			nicknameChecked: this.state.actionType !== 'add',
		}, () => {
			this.props.form.validateFieldsAndScroll({ force: true }, (err, values) => {
				if (err) {
					console.log(err);
					return false;
				}
				console.log(values);
				saveUsers(this.state.actionType, values, this.state.editUserIndex).then(result => {
					// if (result.code === 0) {
					// 	this.setState({
					// 		visible: false,
					// 	});
					// }
				});
			})
		});
	}

	handleCancel = (e) => {
		this.setState({
			visible: false,
		});
	}

	handleCheckedRoles = item => {
		console.log(item);
		this.setState({checkedRoles: item});
	}

	componentDidMount() {
		this.handleGetUsers();

		getRoleBriefList().then(res => {
			console.log(res);
			this.setState({roleList: res})
		})
	}
	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div>
				<Button onClick={this.onAdd} icon='plus' type="primary" style={{ marginBottom: 16, marginRight:16 }}>添加</Button>
				<Button onClick={this.handleDelete} type="danger" icon='delete' style={{ marginBottom: 16 }}>删除</Button>
				<Table className='bg-white' rowSelection={rowSelection} bordered size='small' columns={this.columns} dataSource={this.props.users.list}
					   title={() => '用户列表'}
					   rowKey="id"
					   loading={this.state.loading}
					   pagination={this.state.pagination}
				/>
				<div>
					<Modal
						title={this.state.actionTitle}
						visible={this.state.visible}
						onOk={this.handleSave}
						onCancel={this.handleCancel}
						okText="保存"
						width={660}
						cancelText="取消"
					>
						<Form>
							<FormItem {...formItemLayout} label="用户名">
								{getFieldDecorator('username', {
									rules: [{
										required: true, message: '请输入用户名',},
										{min: 5, message: '用户名长度不能低于5位'}
									],
								})(<Input disabled={this.state.actionType === 'save'} />)}
							</FormItem>
							<FormItem {...formItemLayout} label="昵称">
								{getFieldDecorator('nickname', {
									rules: [{
										required: this.state.nicknameChecked, message: '请输入昵称',},
										{min: 2, message: '昵称长度不能低于2位'}
									],
									initialValue: '',
								})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="密码">
								{getFieldDecorator('password', {
									rules: [{
										required: this.state.passwordChecked, message: '请输入密码',},
										{min: 6, message: '密码长度不能低于6位'}
									],
									initialValue: '',
								})(
									<Input type='password' placeholder={this.state.passwordPlaceholder} />
								)}
							</FormItem>
							<FormItem {...formItemLayout} label="Email">
								{getFieldDecorator('email', {initialValue: ''})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="用户角色">
								{getFieldDecorator('roles', {
									valuePropName: 'checked',
								})(
									<CheckboxGroup onChange={this.handleCheckedRoles} options={this.state.roleList} value={this.state.checkedRoles} />
								)}
							</FormItem>
							<span>
								{getFieldDecorator('id', {
									initialValue: '0',
								})(<Input type='hidden' />)}
							</span>
						</Form>
					</Modal>
				</div>
			</div>
		)
	}
}

export default connect(
	mapStateToProps,
)(Form.create()(UserList))